package threading;

class Counter {
    private int count = 0;
    private Object locker = new Object();
    public void add() {
        synchronized (locker) {
            count++;
        }
    }
    /*
    public void add() {
        synchronized (this) {
            count++;

        }
    }

    synchronized public void add() {
         count++;
    }*/
    public int get () {
        return count;
    }
    synchronized public static void test() {

    }
    public static void test2() {
        synchronized (Counter.class) {

        }
    }
}
public class ThreadDemo13 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        //搞两个线程，两个线程分别对这个 counter 自增 5w 次
        Thread t1 = new Thread( () -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        Thread t2 = new Thread( () -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        t1.start();
        t2.start();
        //等待两个线程执行结束，然后看结果
        t1.join();
        t2.join();

        System.out.println(counter.get());

    }
}
